package org.skydiveapp;

import java.text.MessageFormat;
import java.util.Calendar;
import java.util.Date;

import org.skydiveapplibrary.repository.SettingsRepository;
import org.skydiveapplibrary.ui.InterfaceManager;
import org.skydiveapplibrary.R;
import org.skydiveapplibrary.data.Constants;
import org.skydiveapplibrary.data.RigReminder;
import org.skydiveapplibrary.data.TimeUnit;
import org.skydiveapplibrary.data.RigReminder.DueStatus;
import org.skydiveapplibrary.ui.FormatUtility;
import org.skydiveapplibrary.ui.TimeIntervalDialog;
import org.skydiveapplibrary.ui.TimeIntervalDialog.OnTimeIntervalSetListener;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;

import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;

public class RigReminderEditActivity extends SherlockActivity
{
	// data
    private int interval;
    private TimeUnit intervalUnit;
    private Date lastDoneDate;
	private Boolean isEdit = false;
	private boolean isDualDisplay;
	
	// listeners
    private OnClickListener intervalEditListener = new OnClickListener()
    {
            @Override
            public void onClick(View view)
            {
                    showIntervalDialog();
            }
    };
    private OnTimeIntervalSetListener intervalSetListener = new OnTimeIntervalSetListener()
    {
            @Override
            public void onTimeIntervalSet(TimeIntervalDialog dialog, int interval,
                            TimeUnit timeUnit)
            {
                    updateInterval(interval, timeUnit);
            }
    };
    private OnClickListener dateEditListener = new OnClickListener()
    {
            @Override
            public void onClick(View view)
            {
                    showDateDialog();
            }
    };
    private OnDateSetListener dateSetListener = new OnDateSetListener()
    {
            @Override
            public void onDateSet(DatePicker dialog, int year, int month, int day)
            {
                    Calendar cal = Calendar.getInstance();
                    cal.set(year, month, day);
                    updateLastDoneDate(cal.getTime());
            }
    };
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		SettingsRepository settingsRepository = new SettingsRepository(this);
		if (settingsRepository.getUseLightTheme())
			super.setTheme(R.style.SkydiveAppTheme_Light_Transparent);
		
		super.onCreate(savedInstanceState);
		
		//init ui
		initializeUI();
	}

	private void initializeUI()
	{
		// show view
		setContentView(R.layout.rig_reminder_edit_view);
		
		// set subtitle text
		InterfaceManager.getInstance().setSubtitleText(getSupportActionBar(), 
						getResources().getString(R.string.rig_reminder_header));
	
		isDualDisplay = this.findViewById(R.id.phoneLayout) == null;
		
		// get data
		Bundle extras = getIntent().getExtras();
		isEdit = (extras != null && extras.getBoolean(Constants.EXTRA_RIG_REMINDER_IS_EDIT, false));
		String name = (extras != null && extras.containsKey(Constants.EXTRA_RIG_REMINDER_NAME)) ?
		                extras.getString(Constants.EXTRA_RIG_REMINDER_NAME) : "";
		interval = (extras != null) ? extras.getInt(Constants.EXTRA_RIG_REMINDER_INTERVAL, 0) : 0;
		intervalUnit = (extras != null && extras.containsKey(Constants.EXTRA_RIG_REMINDER_INTERVAL_UNIT)) ?
		                (TimeUnit)extras.getSerializable(Constants.EXTRA_RIG_REMINDER_INTERVAL_UNIT) : TimeUnit.Days;
		lastDoneDate = (extras != null && extras.containsKey(Constants.EXTRA_RIG_REMINDER_LAST_COMPLETED_DATE)) ?
		                (Date)extras.getSerializable(Constants.EXTRA_RIG_REMINDER_LAST_COMPLETED_DATE) : new Date();
		
		// set name
		EditText dField = (EditText)findViewById(R.id.RigReminderDescriptionField);
		dField.setText(name);
		
		// init interval field
		TextView iField = (TextView)findViewById(R.id.RigReminderIntervalField);
		iField.setOnClickListener(intervalEditListener);
		updateInterval(interval, intervalUnit);
		
		// init last done date
		TextView ldField = (TextView)findViewById(R.id.RigReminderLastDoneField);
		ldField.setOnClickListener(dateEditListener);
		updateLastDoneDate(lastDoneDate);
	}
	
	private void showIntervalDialog()
	{
		// create dialog
        TimeIntervalDialog dialog = new TimeIntervalDialog(
        				new ContextThemeWrapper(this, R.style.DialogStyle),
                        interval,
                        intervalUnit,
                        intervalSetListener);
        // show
        dialog.show();
	}
	
	private void showDateDialog()
	{
		 // create date dialog
        Calendar cal = Calendar.getInstance();
        cal.setTime(lastDoneDate);
        DatePickerDialog dialog = new DatePickerDialog(
        				new ContextThemeWrapper(this, R.style.DialogStyle),
                        dateSetListener,
                        cal.get(Calendar.YEAR),
                        cal.get(Calendar.MONTH),
                        cal.get(Calendar.DAY_OF_MONTH));
        // show dialog
        dialog.show();
	}
	
	private void updateInterval(int interval, TimeUnit timeUnit)
    {
        // update local vars
        this.interval = interval;
        this.intervalUnit = timeUnit;
        
        // update ui
        TextView iField = (TextView)findViewById(R.id.RigReminderIntervalField);
        iField.setText(MessageFormat.format("{0} {1}",
                        FormatUtility.toNumericString(interval),
                        getString(intervalUnit.getResourceId())));
        
        // update due by
        updateDueByField();
    }
	
	private void updateLastDoneDate(Date date) 
    {
        // update date
        this.lastDoneDate = date;
        
        // update ui
        TextView ldField = (TextView)findViewById(R.id.RigReminderLastDoneField);
        ldField.setText(FormatUtility.toDateString(this, lastDoneDate));
        
        // update due by
        updateDueByField();
    }
	
	private void updateDueByField()
    {
	    // get due date and due status
	    Date dueDate = RigReminder.getDueDate(interval, intervalUnit, lastDoneDate);
	    DueStatus dueStatus = RigReminder.getDueStatus(dueDate);
	    
	    // update due by field
	    TextView dbField = (TextView)findViewById(R.id.RigReminderDueByField);
	    dbField.setText(FormatUtility.toDateString(this, dueDate));
	    
	    // update color/icon
	    Drawable icon = null;
	    int textStyleId = R.style.FormFieldValueStyle;
	    if (dueStatus == DueStatus.DueSoon)
	    {
	            textStyleId = R.style.DueSoonTextStyle;
	    }
	    else if (dueStatus == DueStatus.PastDue)
	    {
	            textStyleId = R.style.PastDueTextStyle;
	            icon = getResources().getDrawable(R.drawable.skull_small);
	    }
	    dbField.setTextAppearance(this, textStyleId);
	    dbField.setCompoundDrawablesWithIntrinsicBounds(null, null, icon, null);
    }
	
	private void save()
	{
		// get name from field
        EditText dField = (EditText)findViewById(R.id.RigReminderDescriptionField);
        String name = dField.getText().toString();
        
        // set result
        Intent result = new Intent();
        result.putExtra(Constants.EXTRA_RIG_REMINDER_NAME, name);
        result.putExtra(Constants.EXTRA_RIG_REMINDER_INTERVAL, interval);
        result.putExtra(Constants.EXTRA_RIG_REMINDER_INTERVAL_UNIT, intervalUnit);
        result.putExtra(Constants.EXTRA_RIG_REMINDER_LAST_COMPLETED_DATE, lastDoneDate);
        setResult(RESULT_OK, result);
        
        // finish
        close();
	}
	
	private void delete()
	{
		Intent result = new Intent();
        result.putExtra(Constants.EXTRA_RIG_REMINDER_DELETE, true);
        setResult(RESULT_OK, result);
        
        // finish
        close();
	}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	MenuInflater inflater = getSupportMenuInflater();	
    	inflater.inflate(R.menu.menu_save, menu);
        if (isEdit)
        	inflater.inflate(R.menu.menu_delete, menu);

        inflater.inflate(R.menu.menu_back, menu);
        return true;
    }
    
    @Override
    public boolean onPrepareOptionsMenu(Menu menu)
    {
    	menu.findItem(R.id.menu_back).setVisible(isDualDisplay);
    	return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        
		if (itemId == R.id.menu_save)
		{
			save();
			return true;
		}
		else if (itemId == R.id.menu_back)
		{
			close();
			return true;
		}
		else if (itemId == R.id.menu_delete)
		{
			delete();
			return true;
		}
		else
		{
			return super.onOptionsItemSelected(item);
		}
    }
    
    private void close()
    {
    	finish();
    }
    
    @Override
    public void onBackPressed()
    {
    	save();
    }
}
